package org.deyang.tools.amazon;

import java.io.IOException;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Query;
import com.google.appengine.api.taskqueue.Queue;
import com.google.appengine.api.taskqueue.QueueFactory;
import com.google.appengine.api.taskqueue.TaskOptions;

public class EnqueueTwitterTaskServlet extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 2511142216188244896L;
	private static final Logger log = Logger.getLogger(EnqueueTwitterTaskServlet.class.getName());
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
	throws IOException {
		String asin = req.getParameter("asin");
		if (asin != null && !asin.equals("")){
			Query asinq = new Query("AmazonProduct");
			asinq.addFilter("asin", Query.FilterOperator.EQUAL, asin);
			DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
			Entity twitterEntry = datastore.prepare(asinq).asSingleEntity();
			
			
			if (twitterEntry != null){
				twitterEntry.setProperty("isPendingToTwitter", true);
				twitterEntry.setProperty("twitterPostPrice", req.getParameter("saleprice"));
			    twitterEntry.setProperty("twitterSaleText", req.getParameter("saletext"));
			    twitterEntry.setProperty("twitterProductDesc", req.getParameter("twitterproductdesc"));
			    twitterEntry.setProperty("shorturl", req.getParameter("shorturl"));
//			    try {
//					weiboEntry.setProperty("weiboImage", new Blob(ImageService.getImageFromURL(req.getParameter("imgurl"))));
//				} catch (Exception e) {
//					log.warning(e.getMessage());
//				}
			}else{
				twitterEntry = new Entity("AmazonProduct");
				twitterEntry.setProperty("asin", asin);
			    twitterEntry.setProperty("isPendingToTwitter", true);
			    twitterEntry.setProperty("twitterPostPrice", req.getParameter("saleprice"));
			    twitterEntry.setProperty("twitterSaleText", req.getParameter("saletext"));
			    twitterEntry.setProperty("twitterProductDesc", req.getParameter("twitterproductdesc"));
			    twitterEntry.setProperty("shorturl", req.getParameter("shorturl"));
//			    try {
//					weiboEntry.setProperty("weiboImage", new Blob(ImageService.getImageFromURL(req.getParameter("imgurl"))));
//				} catch (Exception e) {
//					log.warning(e.getMessage());
//				}
			}
			datastore.put(twitterEntry);
			
			Queue queue = QueueFactory.getQueue("twitterpostqueue");
		    queue.add(TaskOptions.Builder.withUrl("/twitterpost").param("asin", asin));
		}
	}

}
